﻿namespace CDV.MC.MatrixDriver.WebApp.Service
{
    using Microsoft.AspNetCore.Http;
    using System;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Net.Sockets;

    public interface IHttpClientProvider
    {
        HttpClient GetHttpClient(HttpContext httpContext);

        string GetClientIPAddress(HttpContext httpContext);
    }

    public class HttpClientProvider : IHttpClientProvider
    {
        public string BaseUri { get; set; }

        public const string ClientIPName = "ClientIP";
        public string GetClientIPAddress(HttpContext httpContext)
        {
            var clientIP = IPAddress.IsLoopback(httpContext.Connection.RemoteIpAddress)
                           ? Dns.GetHostEntry(httpContext.Connection.RemoteIpAddress).AddressList.First((ipAddress) =>
                             {
                                 return ipAddress.AddressFamily == AddressFamily.InterNetwork;
                             })
                           : httpContext.Connection.RemoteIpAddress;

            return $"{clientIP}:{httpContext.Connection.RemotePort}";
        }

        public HttpClient GetHttpClient(HttpContext httpContext)
        {
            var httpClient = new HttpClient() { BaseAddress = new Uri(BaseUri/*"http://localhost:9100/"*/) };

            var clientIP = httpContext.Session.GetString(ClientIPName);
            if (string.IsNullOrEmpty(clientIP))
            {
                clientIP = GetClientIPAddress(httpContext).ToString();
            }
            //客户端IP端口设定
            httpClient.DefaultRequestHeaders.Add(ClientIPName, clientIP);
            return httpClient;
        }
    }
}
